/*
Copyright (c) 2009, Heinrich C. Spreiter
All rights reserved.

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

  - Redistributions of source code must retain the above copyright notice,
  this list of conditions and the following disclaimer.
  
  - Redistributions in binary form must reproduce the above copyright notice,
  this list of conditions and the following disclaimer in the documentation
  and/or other materials provided with the distribution.
  
  - Neither the name of the author nor the names of its contributors may be used
  to endorse or promote products derived from this software without specific
  prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package ch.kynlang.compiler.symbol;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import ch.kynlang.compiler.EvaluationException;
import ch.kynlang.compiler.KohYaoNoiLexer;
import ch.kynlang.compiler.tree.KynTree;

/*
 * ComponentSymbol.java
 *
 * @version 0.1 05.01.2010
 * @author HSP spreiter301@gmail.com
 * 
 * Baseclass for all components
 */
public abstract class ComponentSymbol extends Symbol {
	// reference to the parent. can be null if root container
	public ContainerSymbol parentComponent = null;
	// valid properties for this component
	public Map<String, PropertySymbol> properties = null;
	// valid properties for the parent
	public Map<String, PropertySymbol> parentProperties = null;
	// all properties we have defined.
	// will be put into properties or parentProperties
	public List<PropertySymbol> definedProperties = null;
	
	
	public ComponentSymbol(KynTree tree) {
		super(tree);
		KynTree kt = (KynTree) tree.getChild(1);
		this.name = kt.getText();
		properties = new HashMap<String, PropertySymbol>();
		parentProperties = new HashMap<String, PropertySymbol>();
		definedProperties = new LinkedList<PropertySymbol>();
	}
	
	public void addProperty(PropertySymbol property) {
		definedProperties.add(property);
	}
	
	@Override
	public void evaluate() throws EvaluationException {
		// try to add to the parent
		if(parentComponent != null) {
			if(!parentComponent.addChild(this)) {
				throw new EvaluationException(tree, "Can not add " + name + " to " + parentComponent.name + " as child! Maximum childcount: " + parentComponent.maxChildCount);
			}
		}
		// check for WBODY
		if(this instanceof ContainerSymbol && tree.getChildCount() != 4) {
			// Containers needs a WBODY!
			throw new EvaluationException(tree, "Container " + tree.getChild(1).getText() + " must have a widget body");
		} else if(this instanceof UIComponent && tree.getChildCount() != 3) {
			// UIComponent can not have WBODY!
			throw new EvaluationException(tree, "UIComponent " + tree.getChild(1).getText() + " can not have a widget body");
		}
		// now loop over each property, evaluate it
		// and put it into definedProperties
		KynTree pbody = (KynTree) tree.getChild(2);
		for(int i = 0; i < pbody.getChildCount(); i++) {
			KynTree pt = (KynTree) pbody.getChild(i);
			pt.scope = tree.scope;
			
			Symbol s = null;
			switch(pt.getType()) {
				case KohYaoNoiLexer.HASH:
					// macro access
					String macroName = pt.getChild(0).getText();
					// lookup in Symboltable
					s = pt.scope.resolve(macroName);
					if(s == null) {
						throw new EvaluationException(pt, "Macro " + macroName + " is not defined");
					} else if((s instanceof MacroSymbol) == false) {
						throw new EvaluationException(pt, macroName + " is not a macro");
					}
					
					// everything is ok. expand macro
					MacroSymbol macro = (MacroSymbol) s;
					for(PropertySymbol ps : macro.properties) {
						definedProperties.add(ps);
					}
					break;
				case KohYaoNoiLexer.PROPERTY:
					StringBuilder sb = new StringBuilder();
					PropertySymbol ps = new PropertySymbol((KynTree) pt);
					ps.evaluate();
					definedProperties.add(ps);
					break;
			}
		}
		
		// loop over each defined property and
		// check if it's a valid component or parent component property
		for(PropertySymbol ps : definedProperties) {
			// check if it's a parent property
			if(parentProperties.containsKey(ps.name)) {
				// it's a parent property. check if it's compatible
				PropertySymbol pps = parentProperties.get(ps.name);
				if(pps.type.getJavaClass().isAssignableFrom(ps.type.getJavaClass())) {
					parentProperties.put(ps.name, ps);
				} else {
					throw new EvaluationException(ps.tree, "Property " + ps.name + " must be " + pps.type.getFullQualifiedName() + ". Found " + ps.type.getFullQualifiedName() + " (" + tree.getChild(1).getText() + ")");
				}
			} else {
				// check if we can define it in this component
				Class<?> c = getClassFromProperty(type.getJavaClass(), ps.name);
				if(c != null && c.isAssignableFrom(ps.type.getJavaClass())) {
					properties.put(ps.name, ps);
					continue;
				}
				if(this instanceof ContainerSymbol) {
					// check for property on the container class
					ContainerSymbol cons = (ContainerSymbol) this;
					c = getClassFromProperty(cons.container, ps.name);
					if(c != null && c.isAssignableFrom(ps.type.getJavaClass())) {
						cons.directOnContainerClassProperties.put(ps.name, ps);
						continue;
					}
				}
				// invalid property
				throw new EvaluationException(ps.tree, "Property " + ps.name + " of type " + ps.type.getFullQualifiedName() + " is not valid (" + tree.getChild(1).getText() + ")");
			}
			
		}
	}

	private static Class<?> getClassFromProperty(Class<?> clazz, String property) {
		try {
			BeanInfo bd = Introspector.getBeanInfo(clazz);
			for(PropertyDescriptor pd : bd.getPropertyDescriptors()) {
				if(pd.getName().equals(property)) {
					return pd.getPropertyType();
				}
			}
		} catch (IntrospectionException e) {
			return null;
		}
		return null;
	}
}
